import React, { useEffect, useState } from 'react'
import { useParams, useHistory, Link } from 'react-router-dom'
import { currentcity, searchplace } from 'src/api/getData'
import { getStore, setStore, removeStore } from 'src/config/mUtils'
import { Header } from 'src/components'
import { useDispatch } from 'react-redux'
import { RECORD_ADDRESS, SAVE_GEOHASH } from 'src/redux/action-type'
import './index.scss'

const City = () => {
    const dispatch = useDispatch();
    const { cityId } = useParams();
    const history = useHistory();

    const [cityname, setCityName] = useState();
    const [inputVaule, setInputVaule] = useState();
    const [historytitle, setHistoryTitle] = useState(true);
    const [placelist, setPlaceList] = useState([]);
    const [placeNone, setPlaceNone] = useState(false);

    useEffect(() => {
        // 获取搜索记录
        if (getStore('placeHistory')) {
            setPlaceList(JSON.parse(getStore('placeHistory')))
        }
    }, [])

    useEffect(() => {
        // 获取城市信息
        if (cityId) {
            currentcity(cityId).then(res => {

                if (res.latitude && res.longitude) {
                    setCityName(res.name);
                    let geohashNew = res.latitude + ',' + res.longitude
                    setStore('_geohash', geohashNew)//缓存
                    // geohash保存到store
                    dispatch({
                        type: SAVE_GEOHASH,
                        geohash: geohashNew
                    })
                }
            })
        }
    }, [cityId])

    //发送搜索信息inputVaule
    const postpois = (e) => {
        e.preventDefault();
        if (inputVaule) {
            searchplace(cityId, inputVaule).then(res => {
                setHistoryTitle(false);
                setPlaceList(res)
                setPlaceNone(res.length ? false : true)
            })
        }
    }
    /**
    * 点击搜索结果进入下一页面时进行判断是否已经有一样的历史记录
    * 如果没有则新增，如果有则不做重复储存，判断完成后进入下一页
    */
    const nextpage = (index, geohash) => {
        let curHistory = getStore('placeHistory');
        let choosePlace = placelist[index];
        let placeHistory = [];
        if (curHistory) {
            let checkrepeat = false;
            placeHistory = JSON.parse(curHistory);
            placeHistory.forEach(item => {
                if (item.geohash === geohash) {
                    checkrepeat = true;
                }
            })
            if (!checkrepeat) {
                placeHistory.push(choosePlace)
            }
        } else {
            placeHistory.push(choosePlace)
        }
        setStore('placeHistory', placeHistory)
        history.push(`/msite?geohash=${geohash}`);
    }
    const clearAll = () => {
        removeStore('placeHistory');
        setPlaceList([])
    }

    return <div className="page_city">
        <Header
            title={cityname}
            goBack
            changecity={<Link to="/home" className="change_city">切换城市</Link>}
        />
        <form className="city_form">
            <div>
                <input
                    type="search"
                    name="city"
                    placeholder="输入学校、商务楼、地址"
                    className="city_input input_style"
                    required
                    value={inputVaule}
                    onInput={(e) => setInputVaule(e.target.value)}
                />
            </div>
            <div>
                <input type="submit" name="submit" className="city_submit input_style" onClick={postpois} value="提交" />
            </div>
        </form>
        {historytitle && <header className="pois_search_history">搜索历史</header>}
        <ul className="getpois_ul">
            {
                placelist.map((item, index) => {
                    return <li onClick={() => { nextpage(index, item.geohash) }} key={index}>
                        <h4 className="pois_name ellipsis">{item.name}</h4>
                        <p className="pois_address ellipsis">{item.address}</p>
                    </li>
                })
            }
        </ul>
        {historytitle && placelist.length && <footer className="clear_all_history" onClick={clearAll}>清空所有</footer>}
        {placeNone && <div className="search_none_place">很抱歉！无搜索结果</div>}
    </div>
}
export default City